import { reqLogin, reqUserInfo } from '@/api/user'
import { syncSetStorage } from '@/utils/storage'
// 引入store
import { userStore } from '@/store/userStore'
import { ComponentWithStore } from 'mobx-miniprogram-bindings'
import { debounce } from 'miniprogram-licia'

ComponentWithStore({
  // store与页面建立关联
  storeBindings: {
    store: userStore,
    fields: ['token', 'userInfo'],
    actions: ['setToken', 'setUserInfo']
  },

  methods: {
    // 授权登录
    handleLogin: debounce(function () {
      wx.login({
        success: async (res) => {
          // 获取到临时登录code后发请求
          if (res.code) {
            const {
              data: { token }
            } = await reqLogin(res.code)
            // 将token存本地缓存
            syncSetStorage('token', token)
            // 将token存到store中
            this.setToken(token)
            // 获取用户信息
            this.getUserInfo()
            wx.navigateBack()
          } else {
            wx.toast({ title: '授权失败，请重试' })
          }
        }
      })
    }, 300),

    // 获取用户信息
    async getUserInfo() {
      const { data } = await reqUserInfo()
      // mobx数据持久化处理
      syncSetStorage('userInfo', data)
      this.setUserInfo(data)
    }
  }
})
